<template>
  <div class="infoConfig">
    <el-form ref="form" :model="form" :rules="rules">
      <div class="leftLine title">机构信息</div>
      <el-row>
        <el-col :span="5" class="line40">机构</el-col>
        <el-col :span="7" class="line40">
          <!-- <el-form-item v-if="pageType == 'add'" label="" prop="orgName" class="mg-b-0">
            <el-input v-model="form.orgName" :controls="false" style="width:150px" size="small" :step="1" :min="1" :max="10" placeholder="机构名称" />
          </el-form-item> -->
          <el-select v-if="pageType == 'add'" v-model="form.orgName" placeholder="请选择" style="width:150px">
            <el-option
              v-for="item in options"
              :key="item.deptId"
              :label="item.name"
              :value="item.name"
              @click.native="elOptionChange(item.deptId)"
            />
          </el-select>
          <span v-else>{{ form.orgName }}</span>
        </el-col>
        <el-col :span="5" class="line40">业务编号</el-col>
        <el-col :span="7" class="line40">
          <el-form-item label="" prop="orgId" class="mg-b-0">
            <span>{{ form.orgId }}</span>
          </el-form-item>
        </el-col>
      </el-row>
      <div class="leftLine title">
        租户流量余额折扣配置
        <el-button v-if="['edit','add'].includes(pageType)" type="text" @click="addLine('orgDiscountConf')">添加配置</el-button>
      </div>
      <el-form-item label="" prop="orgDiscountConf">
        <AddList v-model="form.orgDiscountConf" :show-add-btn="false" :show-del-btn="pageType != 'detail' && form.orgDiscountConf.length > 1">
          <template v-slot="{item: { item, index }}">
            <div v-if="pageType == 'detail'">
              <span class="mg-r-20">配置{{ index+1 }}</span>
              <span class="mg-r-20">单笔金额≥{{ item.singlePay }}元</span>
              <span class="mg-r-20">租户享受采购流量余额{{ item.discount }}折优惠</span>
            </div>
            <div v-else>
              <span class="mg-r-20">配置{{ index+1 }}</span>
              <span class="mg-r-20">单笔金额≥ <el-input-number v-model="item.singlePay" :controls="false" class="numInput" size="small" :step="1" :min="1" :max="999999999" /> 元</span>
              <span class="mg-r-20">租户享受采购流量余额<el-input-number v-model="item.discount" :controls="false" class="numInput" size="small" :step="1" :min="1" :max="10" />折优惠</span>
            </div>
          </template>
        </AddList>
      </el-form-item>
      <div class="leftLine title">
        平台佣金兑换流量余额比例
      </div>
      <div>
        <el-form-item label="" prop="interactionRatio">
          <div v-if="pageType == 'add' || pageType == 'edit'">
            <!-- <span class="mg-r-20">{{ form.interactionRatio }}:10 即：假设平台佣金{{ form.interactionRatio }}0元全部分账给到租户，从租户账上扣除100流量余额</span> -->
            <span class="mg-r-20">
              <el-input-number v-model="form.interactionRatio" :controls="false" class="numInput" size="small" :step="1" :min="1" :max="99999" />&nbsp;：&nbsp;10
            </span>
          </div>
          <div v-else>
            <span class="mg-r-20">
              <span>{{ form.interactionRatio }}</span>&nbsp;：&nbsp;10
            </span>
          </div>
        </el-form-item>
      </div>
      <div class="leftLine title">
        代理流量余额折扣配置
      </div>
      <el-form-item label="" prop="agtList">
        <AddList v-model="agtList" :show-add-btn="false" :show-del-btn="false">
          <template v-slot="{item: { item, index }}">
            <div v-if="pageType == 'detail'">
              <span class="mg-r-20">{{ item.name }}</span>
              <span class="mg-r-20">享受购买流量余额{{ form[item.key] }}折优惠</span>
            </div>
            <div v-else>
              <span class="mg-r-20">{{ item.name }}</span>
              <span class="mg-r-20">享受购买流量余额<el-input-number v-model="form[item.key]" :controls="false" class="numInput" size="small" :step="1" :min="1" :max="10" />折优惠</span>
            </div>
          </template>
        </AddList>
      </el-form-item>
      <div class="leftLine title">
        代理套餐配置
        <el-button v-if="['edit','add'].includes(pageType)" type="text" @click="addLine('agtConfigList')">添加配置</el-button>
      </div>
      <el-form-item label="" prop="agtConfigList">
        <AddList v-model="form.agtConfigList" :show-add-btn="false" :show-del-btn="pageType != 'detail' && form.agtConfigList.length > 1">
          <template v-slot="{item: { item, index }}">
            <div v-if="pageType == 'detail'">
              <span class="mg-r-20">配置{{ index+1 }}</span>
              <span class="mg-r-20">单次充值固定金额{{ item.rechargeFixMoney }}元</span>
            </div>
            <div v-else>
              <span class="mg-r-20">配置{{ index+1 }}</span>
              <span class="mg-r-20">单次充值固定金额 <el-input-number v-model="item.rechargeFixMoney" :controls="false" class="numInput" size="small" :step="1" :min="1" :max="999999999" /> 元</span>
            </div>
          </template>
        </AddList>
      </el-form-item>
      <div class="leftLine title">
        商户充值金额配置
        <el-button v-if="['edit','add'].includes(pageType)" type="text" @click="addLine('mercConfigList')">添加配置</el-button>
      </div>
      <el-form-item label="" prop="mercConfigList">
        <AddList v-model="form.mercConfigList" :show-add-btn="false" :show-del-btn="pageType != 'detail' && form.mercConfigList.length > 1">
          <template v-slot="{item: { item, index }}">
            <div v-if="pageType == 'detail'">
              <span class="mg-r-20">配置{{ index+1 }}</span>
              <span class="mg-r-20">单次充值固定金额{{ item.rechargeFixMoney }}元</span>
            </div>
            <div v-else>
              <span class="mg-r-20">配置{{ index+1 }}</span>
              <span class="mg-r-20">单次充值固定金额 <el-input-number v-model="item.rechargeFixMoney" :controls="false" class="numInput" size="small" :step="1" :min="1" :max="999999999" /> 元</span>
            </div>
          </template>
        </AddList>
      </el-form-item>
      <div class="leftLine title">
        流量标准资费
      </div>
      <div>
        <el-form-item label="" prop="flowRatio">
          <div v-if="pageType == 'detail'">
            <span class="mg-r-20">1 流量 = {{ form.flowRatio }}次交互</span>
          </div>
          <div v-else>
            <span class="mg-r-20">1 流量 =  <el-input-number v-model="form.flowRatio" :controls="false" class="numInput" size="small" :step="1" :min="1" :max="99999" /> 次交互</span>
          </div>
        </el-form-item>
      </div>
      <div class="leftLine title">
        开户介绍页背景
        <el-button type="text" @click="imgvis = true">查看示例</el-button>
      </div>
      <div>
        <el-form-item label="" prop="openPictureUrl">
          <div v-if="pageType == 'detail'">
            <el-image
              v-if="form.openPictureUrl"
              class="avatar"
              style="width: 100px; height: 100px"
              :src="form.openPictureUrl"
              fit="contain"
            />
          </div>
          <div v-else>
            <el-upload
              class="app-uploader-img-plus"
              :action="actionUrl"
              :show-file-list="false"
              :headers="uploadHeaders"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <el-image
                v-if="form.openPictureUrl"
                class="avatar"
                style="width: 100px; height: 100px"
                :src="form.openPictureUrl"
                fit="contain"
              />
              <i v-else class="el-icon-plus app-uploader-img-plus-icon" />
            </el-upload>
            <div class="tip">建议尺寸375px * 667px，仅支持jpg、jpeg、png格式，最大2MB</div>
          </div>
        </el-form-item>
      </div>
      <div v-if="['edit','add'].includes(pageType)" class="btnList textCenter">
        <el-button size="small" @click="$emit('close')">取消</el-button>
        <el-button type="primary" size="small" @click="submit">保存配置</el-button>
      </div>
    </el-form>

    <el-dialog
      title="背景示例"
      append-to-body
      :visible.sync="imgvis"
      width="30%"
    >
      <div style="text-align:center;">
        <img width="400" src="https://hyyxboss.oss-cn-shenzhen.aliyuncs.com/kd/20221108/4cdefffe-8cf2-4371-b0a8-43e0f535a10e.png" alt="">
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="imgvis = false">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import AddList from '@/components/AddList/index.vue'
import { update, insert, orgDeptList } from '@/api/flowConf'
import { imgUploadUrl } from '@/api/upload'
export default {
  components: { AddList },
  props: {
    infoConfig: {}
  },
  data() {
    return {
      text: '',
      imgvis: false,
      options: [],
      actionUrl: imgUploadUrl,
      uploadHeaders: {},
      form: {
        orgDiscountConf: [],
        agtConfigList: [],
        mercConfigList: []
      },
      agtList: [
        { name: '运营中心', key: 'operateDiscount' },
        { name: '一级代理', key: 'oneAgtDiscount' },
        { name: '二级代理', key: 'twoAgtDiscount' },
        { name: '三级代理', key: 'threeAgtDiscount' }
      ],
      rules: {
        orgDiscountConf: [{ validator: this.valid, trigger: 'change' }],
        agtList: [{ validator: this.valid, trigger: 'change' }],
        agtConfigList: [{ validator: this.valid, trigger: 'change' }],
        mercConfigList: [{ validator: this.valid, trigger: 'change' }],
        orgName: [{ validator: this.valid, trigger: 'change' }],
        orgId: [{ validator: this.valid, trigger: 'change' }],
        // flowRatio: [{ validator: this.valid, trigger: 'change' }],
        interactionRatio: [{ validator: this.valid, trigger: 'change' }],
        openPictureUrl: [{ validator: this.valid, trigger: 'change' }]
      }
    }
  },
  computed: {
    pageType() { return this.infoConfig.type }
  },
  mounted() {
    this.getOrgDeptList()
    if (this.pageType === 'add') {
      this.form = {
        orgDiscountConf: [],
        agtConfigList: [],
        mercConfigList: []
      }
    } else {
      const baseData = JSON.parse(JSON.stringify(this.infoConfig.data))
      this.form = {
        ...baseData
      // mercConfigList: baseData.orgPackageConf.filter(v => v.roleType == 2),
      // agtConfigList: baseData.orgPackageConf.filter(v => v.roleType == 1)
      }
    }
    console.log('this.form', this.form)
  },
  methods: {
    handleAvatarSuccess(res, file) {
      if (res.code === 0) {
        this.form.openPictureUrl = res.data.baseUrl + res.data.path
      } else {
        this.$message.error(res.msg)
      }
    },
    // 上传前处理
    beforeAvatarUpload(file) {
      return this.$beforeUploadImg(file, this, 0, 0, 2)
    },
    elOptionChange(e) {
      this.$set(this.form, 'orgId', e)
    },
    // 获取未配置代理流量的机构列表
    getOrgDeptList() {
      orgDeptList().then(res => {
        // console.log('获取未配置代理流量的机构列表', res)
        if (res.succeed) {
          this.options = res.data
        }
      })
    },
    submit() {
      if (this.form.orgName) {

      } else {
        this.$message.error('请选择机构')
        return
      }
      this.$refs['form'].validate((valid) => {
        if (valid) {
          console.log('form', this.form)
          const orgBaseInfo = {
            'flowRatio': this.form.flowRatio,
            'interactionRatio': this.form.interactionRatio,
            'id': this.form.id,
            'oneAgtDiscount': this.form.oneAgtDiscount,
            'operateDiscount': this.form.operateDiscount,
            'optUser': this.form.optUser,
            'orgId': this.form.orgId,
            'orgName': this.form.orgName,
            'threeAgtDiscount': this.form.threeAgtDiscount,
            'openPictureUrl': this.form.openPictureUrl,
            'twoAgtDiscount': this.form.twoAgtDiscount
          }
          const orgDiscountConf = this.form.orgDiscountConf.map(v => {
            return { ...v, 'orgId': this.form.orgId }
          })
          const orgPackageConf = [
            ...this.form.agtConfigList,
            ...this.form.mercConfigList
          ].map(v => {
            return { ...v, 'orgId': this.form.orgId }
          })

          console.log('orgBaseInfo', orgBaseInfo, orgDiscountConf, orgPackageConf)
          console.log('this.pageType', this.pageType)
          if (this.pageType === 'add') {
            insert({
              orgBaseInfo, orgDiscountConf, orgPackageConf
            }).then(res => {
              this.$message.success('操作成功！')
              this.$emit('sucClose')
            })
          } else {
            update({
              orgBaseInfo, orgDiscountConf, orgPackageConf
            }).then(res => {
              this.$message.success('操作成功！')
              this.$emit('sucClose')
            })
          }
        } else {
          this.$message.error('表单信息填写有误，请重新检查！')
          return false
        }
      })
    },
    valid(rule, value, callback) {
      const { field } = rule
      let text = ''
      switch (field) {
        case 'orgDiscountConf': {
          // 租户流量余额折扣配置
          if (this.form.orgDiscountConf.length) {
            this.form.orgDiscountConf.forEach((item, index) => {
              if (!item.singlePay || !item.discount) {
                text += `配置${index + 1}信息不完整 `
              }
            })
          } else {
            text = '至少填写一条配置'
          }
          text ? callback(text) : callback()
          break
        }
        case 'orgName': {
          if (!this.form.orgName) {
            text = '请输入机构名称'
          }
          text ? callback(text) : callback()
          break
        }
        case 'openPictureUrl': {
          if (!this.form.openPictureUrl) {
            text = '请上传开户介绍页背景'
          }
          text ? callback(text) : callback()
          break
        }
        case 'orgId': {
          if (!this.form.orgId) {
            text = '请输入业务编号'
          }
          text ? callback(text) : callback()
          break
        }
        case 'agtList': {
          // 代理流量余额折扣配置
          this.agtList.forEach(item => {
            const _data = this.form[item.key]
            if (!_data) {
              text += `请输入${item.name}折扣配置 `
            }
          })
          text ? callback(text) : callback()
          break
        }
        case 'agtConfigList': {
          // 代理套餐配置
          if (this.form.agtConfigList.length) {
            this.form.agtConfigList.forEach((item, index) => {
              if (!item.rechargeFixMoney) {
                text += `配置${index + 1}信息不完整 `
              }
            })
          } else {
            text = '请配置 代理套餐配置'
          }
          text ? callback(text) : callback()
          break
        }
        case 'mercConfigList': {
          // 代理套餐配置
          if (this.form.mercConfigList.length) {
            this.form.mercConfigList.forEach((item, index) => {
              if (!item.rechargeFixMoney) {
                text += `配置${index + 1}信息不完整 `
              }
            })
          } else {
            text = '请配置 商户开户门槛&充值金额配置'
          }
          text ? callback(text) : callback()
          break
        }
        // case 'flowRatio': {
        //   // 流量标准资费
        //   if (!this.form.flowRatio) {
        //     text = '请配置 流量标准资费'
        //   }
        //   text ? callback(text) : callback()
        //   break
        // }
        case 'interactionRatio': {
          // 流量兑换交互次数比例
          if (!this.form.interactionRatio) {
            text = '请配置 流量兑换交互次数比例'
          }
          text ? callback(text) : callback()
          break
        }
        default:
          break
      }
    },
    addLine(type) {
      switch (type) {
        case 'orgDiscountConf':
          this.form.orgDiscountConf.push({
            singlePay: 0,
            discount: 1
          })
          break
        case 'agtConfigList':
          this.form.agtConfigList.push({
            rechargeFixMoney: 1,
            roleType: 1
          })
          break
        case 'mercConfigList':
          this.form.mercConfigList.push({
            rechargeFixMoney: 1,
            roleType: 2
          })
          break
        default:
          break
      }
    }
  }

}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.tip{
  font-size: 12px;
}

.app-uploader-img-plus {
  width: 100px;
  height: 100px;
  border: 1px dotted #ddd;
  .avatar{
    width: 100px;
    height: 100px;
  }
  .app-uploader-img-plus-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }
}
.infoConfig{
  padding: 30px;
  .line40{
    line-height: 40px;
  }
  .title{
    font-size: 15px;
    color: #000;
    margin: 30px 0;
  }
  .numInput{
    width: 100px;
    margin: 0 10px;
  }
}
</style>
